Ext.namespace("Dudley");
Ext.namespace("Dudley.lims");

Dudley.lims.YADStrain = function() {

    var myYADData = [];
    var yadForm = {};
    var yadPanel = {};
    var searchResultsGrid = {};
    var yadHash = null;
    var yadCount = null;
    var yadMaxNum = null;
    var yadBox = null;
    var yadPosition = null;
    var yadStore = null;
    var yadLoaded = false;
    var pagingBar = null;
    var searchInput = 'YAD';
    var searchOption = 'yadFields';
    var spotlightMenu = sptlght.utils.SpotlightUtils.getSpotlightMenu("yadspotlightmenuid");

    Ext.form.Field.prototype.msgTarget = 'side';

    function initYADStore(failedCb, callback) {
        loadYADSearchResult(0, null, callback);
    }

    function loadYADSearchResult(index, searchResultJSON, callback) {
        yadStore = loadSolrSearchResult("YAD", getYADPagingColumns(), yadSolrTranslator, index, searchResultJSON, callback());
		yadStore.load({params:{start:0, limit:10}}, callback());
    }

    function goSearch(index, yadSearchInput, yadSearchOption) {        
        if (yadSearchInput == '') {
            	yadSearchInput = "YAD";            
        }           
        if (yadSearchOption == null || yadSearchOption == 'All' || yadSearchOption == '') {
            yadSearchOption = "yadFields";
        }
        var searchUrl = getSolrSearchUrl(getLuceneTerm("yadFields", yadSearchInput), 1000, yadFields);
        var searchWin = getSearchLoadingWindow("yad-");                
        searchWin.on("show", function () {
            var sb = Ext.getCmp("yad-search-statusbar");
            sb.showBusy();
        });
        searchWin.show();
        Ext.Ajax.request({
            url: searchUrl,
            method: "GET",
            success: function(response) {
                var searchResultObj = Ext.util.JSON.decode(response.responseText);
                loadYADSearchResult(index, searchResultObj.response, function() {
                    Ext.getDom("sample-search-result-list").innerHTML = "";
                    Ext.getDom("yo-form").innerHTML = "";
                    searchWin.close();
                    renderYADSearchResult();
                });
            },
            failure: function() {
                eventManager.fireStatusMessageEvent({ text: "Search Results failed for url:" + searchUrl, level: "error" });
            }
        });
    }

    function loadYADPanel() {
    	var yadSearchForm = getSearchForm("yadSearchButtonId", "yadSearchInputId", null);
        Ext.getCmp("yadSearchButtonId").addListener("click", function(){
			goSearch(0, Ext.getCmp("yadSearchInputId").getValue(), "yadFields");		
		});
		
        var tbarButtons = [
            {
                id: 'showYADSearchResultsId',
                name: 'showYADSearchResults',
                disabled: true,
                text: '<--Search Results',
                icon: "images/back-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            renderYADSearchResult();
                        }
                }
            },
            {
                id: 'searchAllYADId',
                name: 'searchAllYAD',
                disabled: false,
                text: 'View All Records',
                icon: "images/search-blue.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Ext.getDom("yo-form").innerHTML = "";
                            goSearch(0, '*', 'All');
                        }
                }
            },
            {
                id: 'createNewYADId',
                name: 'createNewYAD',
                text: 'Create New YAD',
                icon: "images/add-green.png",
                cls:'x-btn-text-icon',
                listeners: {click:
                        function() {
                            Dudley.lims.YADStrain.loadNewYAD();
                        }
                }
            }
        ];
        yadPanel = new Ext.Panel({
            id: "yadPanelId",
            autoHeight: true,
            border: true,
            renderTo: "yad-panel",
            title: "Lab Strain",
            header: false,
            tbar: tbarButtons,
            items: yadSearchForm
        });
        yadPanel.on("activate", function () {
            Ext.getDom("yo-form").innerHTML = "";
            Ext.getDom("yad-panel").innerHTML = "";
            Ext.getDom("yad-form").innerHTML = "";
            Ext.getDom("sample-search-result-list").innerHTML = "";
            goSearch(0, "YAD", "yadFields");
            renderYADSearchResult();
        });
    }

    function postYADStrain(createNew) {
        var yadPostJson = new Object();
        var boxNumber = Ext.getCmp("yadBoxNumberId").getValue();
        var position = Ext.getCmp("yadPositionId").getValue();
        var strainName = Ext.getCmp("yadStrainNameId").getValue();
        yadPostJson["yadKey"] = strainName;
        yadPostJson["yadAlias"] = Ext.getCmp("yadAliasId").getValue();
        yadPostJson["yadMatingType"] = Ext.getCmp("yadMatingTypeId").getValue();
        yadPostJson["yadGenotype"] = Ext.getCmp("yadGenotypeId").getValue();
        yadPostJson["yadContributor"] = Ext.getCmp("yadContributorId").getValue();
        yadPostJson["yadParent"] = Ext.getCmp("yadStrainParentsId").getValue();
        yadPostJson["yadSource"] = Ext.getCmp("yadStrainSourceId").getValue();
        yadPostJson["yadBoxNumber"] = boxNumber;
        yadPostJson["yadIsbNumber"] = Ext.getCmp("isbYadBoxNumberId").getValue();
        yadPostJson["yadPosition"] = position;
        yadPostJson["yadDateFrozen"] = Ext.getCmp("yadDateFrozenId").getRawValue();
        yadPostJson["yadComments"] = Ext.getCmp("commentsYADId").getRawValue();
        var yadCallback = function() {
            var yadBoxVal = yadBox;
            if (boxNumber >= yadBox) {
                yadBoxVal = boxNumber;
            }
            var yadPositionVal = yadPosition;
            if (isNewPosition(yadPosition, position)) {
                yadPositionVal = position;
            }
            limsadmin_obj["limsadminYadCount"] = yadCount; 
            limsadmin_obj['limsadminYadMaxNum'] = yadMaxNum;
            limsadmin_obj['limsadminYadBoxNum'] = yadBoxVal;
            limsadmin_obj['limsadminYadPosition'] = yadPositionVal;            
            postSolrUpdates(limsadmin_obj, function(){
                Ext.Msg.alert('Info', "New YAD Strain " + strainName + ' Added Successfully');
                Ext.getDom("yo-form").innerHTML = "";
                goSearch(0, strainName, "yadKey");
            });                        
        };
        if (!createNew) {
            yadCallback = function() {
                Ext.Msg.alert('Info', strainName + ' Updated Successfully');
                var searchResultsButton = Ext.getCmp("showYADSearchResultsId");
                searchResultsButton.disable();
            };
        }
        postSolrUpdates(yadPostJson, yadCallback);
    }

    function loadCreateYADStrain(yadHash, callback) {
        var createNew = true;
        var portalPanel = new Ext.Panel({});
        var buttons = [
            {
                id: 'createButton',
                name: 'createButton',
                text: 'Create',
                listeners: {click:
                        function() {
                            if (validateCreateWildStrain('YAD')) {
                                postYADStrain(createNew);
                            }
                        }
                }
            }
        ];
        if (yadHash != null && yadHash["clone"] == undefined) {
            if (yadHash.genotype != undefined && yadHash.genotype == 'Record Deleted') {
                buttons = [];
            } else {
                buttons = [
                    {
                        id: 'updateYADButtonId',
                        name: 'updateYADButton',
                        text: 'Update',
                        listeners: {click:
                                function() {
                                    if (validateCreateWildStrain('YAD')) {
                                        postYADStrain(!createNew);
                                    }
                                }
                        }
                    }
                ];
            }
            if (yadHash.sequencingData == null) {
                yadHash.sequencingData = "";
            }
            if (yadHash.phenotypeData == null) {
                yadHash.phenotypeData = "";
            }
            if (yadHash.comments == null) {
                yadHash.comments = "";
            }
            if (yadHash.rnaData == null) {
                yadHash.rnaData = "";
            }
            if (yadHash.proteomicsData == null) {
                yadHash.proteomicsData = "";
            }
            if (yadHash.imaging == null) {
                yadHash.imaging = "";
            }
            portalPanel = new Ext.Panel({
                id: "yadImagePanelId",
                autoHeight: true,
                title: "Strain Meta Data",
                autoWidth: true,
                header: true,
                html: "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Image View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Sequence View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>Proteomics View Portal</a>"
                        + "&nbsp;" + "<a href='javascript:placeHolder()'><img src='images/search-blue.png' border='0'>RNA View Portal</a>"
            });
        } else {
	    if (yadHash == null )
            	yadHash = new Object();
            var yadMaxInt = parseInt(yadMaxNum);
            yadMaxInt = yadMaxInt + 1;
            var yadCountInt = parseInt(yadCount);
            yadCountInt = yadCountInt + 1;
            yadCount = yadCountInt + "";
            yadHash.boxNumber = yadBox;
            yadHash.position = getNextPosition(yadPosition);
            if (yadPosition == "I9") {
                yadHash.boxNumber = parseInt(yadBox) + 1;
            }
	    if (yadHash.clone != undefined)
		yadHash.comments = yadHash.comments + " cloned from " + yadHash.name; 		
            yadHash.name = 'YAD' + yadMaxInt;
            yadMaxNum = yadMaxInt + "";
	    initStrainJson(yadHash);
        }
        var matingTypeData = getMatingTypeArray();
        var matingTypeStore = new Ext.data.SimpleStore({
            fields: ['key', 'value'],
            data : matingTypeData
        });
        var comboMatingType = new Ext.form.ComboBox({
            store: matingTypeStore,
            name: 'yadMatingType',
            id: 'yadMatingTypeId',
            fieldLabel: 'Mating Type',
            displayField:'value',
            valueField:'key',
            typeAhead: true,
            mode: 'local',
            triggerAction: 'all',
            value:yadHash.matingType,
            forceSelection:true,
            selectOnFocus:true
        });
        yadForm = new Ext.form.FormPanel({
            id: 'yadForm',
            method: 'POST',
            autoHeight: true,
            autoScroll: true,
            border: true,
            buttonAlign: 'left',
            buttons: buttons,
            tbar: [
               {
                    id: 'detailSpotlightYADId',
                    disabled: !createNew,
                    text: 'Spotlight',
                    icon: "images/add-green.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Add to spotlight',
                    listeners: {
                        click: function() {
                            var selectedArray = [yadHash.name, yadHash.name, yadHash.alias];
                            sptlght.utils.SpotlightUtils.setSelectedRecord(selectedArray);
                            sptlght.utils.SpotlightUtils.setSource("yad");
                            sptlght.utils.SpotlightUtils.handleAddToSpotlight();
                        }
                    }
                },
		{
                    id: 'cloneYOId',
                    disabled: !createNew,
                    text: 'Clone',
                    icon: "images/hourglass.png",
                    cls:'x-btn-text-icon',
                    tooltip: 'Clone',
                    listeners: {
                        click: function() {
                            yadHash["clone"] = 1;
			    createNew = true;	
			    getSolrLimsAdmin(setYadAdmin);
                        }
                    }
                }
            ],
            items: [
                new Ext.form.FieldSet({
                    autoHeight: true,
                    border: false,
                    items: [
                        new Ext.form.TextField({
                            id: "yadStrainNameId",
                            fieldLabel: "Key",
                            name: "yadStrainName",
                            value: yadHash.name,
                            width: 500,
                            readOnly: true,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Required: A YAD number that uniquely identifies this version of this strain (for example duplicate copies of the same strain are' +
                                              ' assigned different YAD numbers), the field is system generated and can not be changed.'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "yadAliasId",
                            fieldLabel: "Alias",
                            name: "yadStrainAlias",
                            value: yadHash.alias,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Required: Alias is a name by which the strain and its derivatives is known to the outside world (e.g. RM11-1a), this identifier is ' +
                                              'not necessarily unique (for example we may have several copies of RM11-1a).'
                                    });
                                }
                            }
                        }),
                        comboMatingType,
                        new Ext.form.TextField({
                            id: "yadGenotypeId",
                            fieldLabel: "Genotype",
                            name: "yadStrainGenotype",
                            value: yadHash.genotype,
                            width: 500,
                            allowBlank: false
                        }),
                        new Ext.form.TextField({
                            id: "yadStrainSourceId",
                            fieldLabel: "Source",
                            name: "yadStrainSource",
                            value: yadHash.strainSource,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain source - lab/institution'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "yadContributorId",
                            fieldLabel: "Contributor",
                            name: "yadContributor",
                            value: yadHash.contributor,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain contributor - person'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "yadStrainParentsId",
                            fieldLabel: "Parents",
                            name: "yadStrainParents",
                            value: yadHash.strainParents,
                            width: 500,
                            allowBlank: true
                        }),
                        new Ext.form.TextField({
                            id: "yadBoxNumberId",
                            fieldLabel: "Box Number",
                            name: "yadBoxNumber",
                            value: yadHash.boxNumber,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain box number'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "isbYadBoxNumberId",
                            fieldLabel: "ISB Box Number",
                            value: yadHash.isbBoxNumber,
                            width: 500,
                            allowBlank: false,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'ISB Assigned Strain box number'
                                    });
                                }
                            }
                        }),
                        new Ext.form.TextField({
                            id: "yadPositionId",
                            fieldLabel: "Position",
                            name: "yadPosition",
                            value: yadHash.position,
                            width: 500,
                            allowBlank: true,
                            listeners: {
                                render: function(c) {
                                    Ext.QuickTips.register({
                                        target: c,
                                        title: '',
                                        text: 'Strain box position'
                                    });
                                },
                                change : function (f, nv, ov) {
                                    if (ov != "") {
                                        //Ext.Msg.alert("warning", "Be aware that you are updating a required/system generated box position");
                                    }
                                }
                            }
                        }),
                        new Ext.form.DateField({
                            id: "yadDateFrozenId",
                            fieldLabel: "Date Frozen",
                            name: "yadDateFrozen",
                            value: yadHash.dateFrozen,
                            size: 20,
                            allowBlank: true
                        }),
                        {
                            xtype:'htmleditor',
                            id:'commentsYADId',
                            value: yadHash.comments,
                            fieldLabel:'Comments ' + '<br><i><font size=-2>Relevant information about the strain not covered in other fields</font></i>',
                            height:100,
                            labelSeparator: '',
                            anchor:'98%',
                            listeners: {
                                activate: function(e) {
                                    if (yadHash.comments == undefined || yadHash.comments == "") {
                                        e.execCmd('delete');
                                    }
                                }
                            }
                        }
                    ]
                })
            ]
        });
        callback();
    }

    function doSearch() {
        renderYADSearchResult();
    }

    // render the grid to the specified div in the page
    function renderYADSearchResult() {
        var searchResultsButton = Ext.getCmp("showYADSearchResultsId");
        if (searchResultsButton != null || searchResultsButton != undefined) {
            searchResultsButton.disable();
        }
        var mytbar = [
            {
                id: 'seq2CSVId',
                text: 'Export2CSV',
                icon: "images/check-green.png",
                cls:'x-btn-text-icon',
                tooltip: 'Export search results to csv',
                listeners: {click:
                        function() {
                            Dudley.lims.YADStrain.toCSV();
                        }
                }
            }
        ];
        pagingBar = new Ext.PagingToolbar({
            pageSize: 10,
            store: yadStore,
            displayInfo: true,
            displayMsg: 'Displaying strains {0} - {1} of {2}',
            emptyMsg: "No strains to display"
        });
        searchResultsGrid = new Ext.grid.GridPanel({
            id: "yadSearchResultsId",
            store: yadStore,
            columns: getYADColumnHeaders(),
            stripeRows: true,
            autoExpandColumn: 'name',
            autoHeight: true,
            width: 800,
            title: 'YADStrains',
            renderTo: "sample-search-result-list",
            tbar: mytbar,
            enableDragDrop   : true,
            bbar: pagingBar
        });
        searchResultsGrid.on("rowcontextmenu", onMessageContextMenu);
        searchResultsGrid.on("celldblclick", function (g, ri, ci, e) {
            var searchResultsButton = Ext.getCmp("showYADSearchResultsId");
            searchResultsButton.enable();
            yadHash = new Object();
            populateStrainJson(yadHash, g);
            var resourceUri = "/addama-rest/dudley-sample/path/datasource/YAD/" + yadHash.name;
            Ext.Ajax.request({
                url: resourceUri + "/mayUpdate",
                method: "GET",
                params: {
                    "user_uri": LoggedInUser.userUri
                },
                success: function() {
                    loadCreateYADStrain(yadHash, function() {
                        yadFormRender();
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Read only access allowed", level: "info" });
                    loadCreateYADStrain(yadHash, function() {
                        var updateYADButton = Ext.getCmp("updateYADButtonId");
                        if (updateYADButton != undefined) {
                            updateYADButton.hidden = true;
                        }
                        var deleteYADButton = Ext.getCmp("deleteYADButtonId");
                        if (deleteYADButton != undefined) {
                            deleteYADButton.hidden = true;
                        }
                        yadFormRender();
                    });
                }
            });
        });
    }

    function onMessageContextMenu(grid, rowIndex, e) {
        var activePage = Math.ceil((pagingBar.cursor + pagingBar.pageSize) / pagingBar.pageSize);
        var realIndex = (activePage - 1) * pagingBar.pageSize + rowIndex;
        //selectedRecord = yadStore.allData.items[realIndex].json;
        sptlght.utils.SpotlightUtils.setSelectedRecord(yadStore.allData.items[realIndex].json);
        sptlght.utils.SpotlightUtils.setSource("yad");
        e.preventDefault();
        e.stopEvent();
        var coords = e.getXY();
        spotlightMenu.showAt([coords[0], coords[1]]);
    }

    function yadFormRender() {
        Dudley.lims.samplemgr.getHousingPanel().activate(yadPanel);
        Ext.getDom("sample-search-result-list").innerHTML = "";
        Ext.getDom("yo-form").innerHTML = "";
        yadForm.render("yo-form");
    }
    
    function setYadAdmin(jsonObj){
    	limsadmin_obj =  jsonObj;
    	yadCount = jsonObj.limsadminYadCount;
        yadMaxNum = jsonObj.limsadminYadMaxNum;
        yadBox = jsonObj.limsadminYadBoxNum;
        yadPosition = jsonObj.limsadminYadPosition;
        if (yadHash != null && yadHash.clone == undefined){
        	yadHash = null;
	}
        Ext.getCmp("showYADSearchResultsId").enable();
        loadCreateYADStrain(yadHash, function() {
                Ext.getDom("sample-search-result-list").innerHTML = "";
                Ext.getDom("yo-form").innerHTML = "";
                yadForm.render("yo-form");
        });                       
     }                   

    // public
    return {
        initYAD: function(failedCB) {
            //perl GET.pl http://ravioli-2:8080/addama-rest/dudley-sample/path/datasource/YAD/search?FREE_TEXT='*'&PROJECTION='matingType'&PROJECTION='alias'&PROJECTION='genotype'
            initYADStore(failedCB, function() {
                eventManager.fireStatusMessageEvent({ text: "Finishing init YADStore", level: "info" });
            });
        },

        getYADPanel: function() {
            loadYADPanel();
            return yadPanel;
        },
        setYADLoaded: function(boo) {
            yadLoaded = boo;
        },
        toCSV: function() {
            var csvText = "yadKey,yadAlias,yadMatingType,yadGenotype,yadParent,yadBoxNumber,yadIsbNumber,yadPosition,yadDateFrozen,yadContributor,yadSource,yadComments" + breakDelimiter;
            myYADData.sort(function(a, b) {
                return a[0] - b[0];
            });
            for (var c = 0; c < myYADData.length; c++) {
                var cArray = myYADData[c];
                for (var ci = 0; ci < cArray.length; ci++) {
                    if (cArray[ci] == undefined || cArray[ci] == null) {
                        cArray[ci] = "";
                    }
                    cArray[ci] = cArray[ci] + "";
                    cArray[ci] = cArray[ci].replace(/'/g, "");
                    cArray[ci] = '"' + cArray[ci] + '"';
                    cArray[ci] = cArray[ci].replace(/YAD /, "YAD");
                }
                csvText = csvText + "" + cArray[1] + "," + cArray[2] + "," + cArray[4] + "," + cArray[5] + "," + cArray[7]
                        + "," + cArray[8] + "," + cArray[13] + "," + cArray[12] + "," + cArray[9] + ","
                        + cArray[10] + "," + cArray[6] + "," + cArray[11] + breakDelimiter;
            }
            export2Csv("YADSearchedResults.csv", csvText, "yad2Csv");
        },
        setCrossingSearchParams: function(myParam, myOption) {
            searchInput = myParam;
            searchOption = myOption;
        },
        getYADStore: function() {
            return yadStore;
        },
        loadNewYAD: function() {
            Ext.getDom("yo-form").innerHTML = "";
            if (LoggedInUser.userUri == "/addama-users/users/public@systemsbiology.org") {
                Ext.Msg.alert("warning", "Yo do not have permission to create new strains");
            } else {
            	getSolrLimsAdmin(setYadAdmin);            	              
            }
        },
        loadSearchResult: function() {
            Ext.getDom("sample-search-result-list").innerHTML = "";
            renderYADSearchResult();
        },
        loadStrain: function(yadKey) {
            Ext.Ajax.request({
                url: getSolrSearchUrl("yadKey:" + yadKey, 1, yadFields),
                method: "GET",
                success: function(response) {
                    var yadHash = {};
                    var resp = Ext.util.JSON.decode(response.responseText);
                    populateSingleYADViaSearch(yadHash, resp.response.docs[0]);                    
                    yadHash.name = yadKey;
                    loadCreateYADStrain(yadHash, function() {
                        yadFormRender();
                    });
                },
                failure: function() {
                    eventManager.fireStatusMessageEvent({ text: "Error retrieving data for " + yadKey, level: "error" });
                    Ext.Msg.alert("error", "Error retrieving data for " + yadKey);
                }
            });
        },
        setArrayData: function(data) {
                    myYADData = data;
         }

    };
}();
